<?php

namespace app\common;

use think\Config;
use think\Exception;

class Token
{
    public static $key = 'shsytour.cn';
    
    /**
     * 校验sign
     * @return [type] [description]
     */
    public static function checkToken($data)
    {
        if (isset($data['sign']) && $data['sign'] === self::mixSign($data)) {
            return true;
        }
        throw new Exception("Source check error >" . $data['sign'] . '|' . self::mixSign($data), 1);
    }

    public static function createToken($data)
    {
        return self::mixSign($data);
    }

    /**
     * 组合sign
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    protected static function mixSign($data)
    {
        $data = array_diff_key($data, array_flip(['_url', 'sign', 's', '_token', 'action']));
        ksort($data);

        $str = '';
        foreach ($data as $k => $value) {
            $value = urldecode($value);
            if ($value || $value === '0') {
                $str .= $k . $value;
            }
        }

        $str .= 'key' . Config::get('KEY') ? : self::$key;
        return md5($str);
    }
}
